package com.lhh.springcommon.utils;

import com.lhh.springcommon.exception.CustomException;
import com.lhh.springcommon.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 异常处理器
 * @author 李厚航
 */
@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {
    @ExceptionHandler(value = CustomException.class)
    public Response<String> handleCustomException(CustomException e){
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        CodeEnum codeEnum = e.getCodeEnum();
        log.error(codeEnum.getMsg());
        return new Response<>(codeEnum.getCode(), codeEnum.getMsg(), request.getHeader("requestId"),null);
    }

    @ExceptionHandler(value = Exception.class)
    public Response<String> handleException(Exception e){
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        log.error("{}:{}",CodeEnum.REQUEST_ERROR.getMsg(),e.getMessage());
        return new Response<>(CodeEnum.REQUEST_ERROR.getCode(), CodeEnum.REQUEST_ERROR.getMsg(),request.getHeader("requestId"),null);
    }
}
